package mgrclient

import (
	"github.com/rs/zerolog/log"
	apiv1 "gomod.alauda.cn/mysql-mgr-operator/api/v1"
	apiv1a1 "gomod.alauda.cn/mysql-mgr-operator/api/v1alpha1"
	rdsv1 "gomod.alauda.cn/rds-operator/api/v1"
	corev1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/runtime"
	utilruntime "k8s.io/apimachinery/pkg/util/runtime"
	kubeScheme "k8s.io/client-go/kubernetes/scheme"
	"k8s.io/client-go/rest"
	ctrl "sigs.k8s.io/controller-runtime"
	"sigs.k8s.io/controller-runtime/pkg/client"
	"sync"
)

var (
	scheme     = runtime.NewScheme()
	config     = ctrl.GetConfigOrDie()
	kubeClient client.Client
)

func init() {
	utilruntime.Must(kubeScheme.AddToScheme(scheme))
	utilruntime.Must(apiv1.AddToScheme(scheme))
	utilruntime.Must(apiv1a1.AddToScheme(scheme))
	utilruntime.Must(rdsv1.AddToScheme(scheme))
	config.QPS = 1000
	config.Burst = 2000
	config.APIPath = "api"
	config.GroupVersion = &corev1.SchemeGroupVersion
	config.NegotiatedSerializer = kubeScheme.Codecs
}

func Config() *rest.Config {
	return config
}

func Scheme() *runtime.Scheme {
	return scheme
}

var once sync.Once

func Client() client.Client {
	once.Do(func() {
		opt := client.Options{
			Scheme: Scheme(),
			Mapper: nil,
			Opts:   client.WarningHandlerOptions{},
		}
		c, err := client.New(Config(), opt)
		if err != nil {
			log.Fatal().Err(err).Msg("can not create client")
			return
		}
		kubeClient = c
	})
	return kubeClient
}
